﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Web;
using System.Threading.Tasks;
using System.Data;
using BartonExtension;
using ResponseObject;
using MySql.Data.MySqlClient;
using MySql.Data;
using SQLWrapper;

using WSServer;

using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin;

using Model;
using WeixinModel;

namespace XiJiaXi.Controllers
{
    public class OAuth2Controller : ApiController
    {
        [HttpGet]
        public ZKResponse GetAuthUrl(string url,string state)
        {
            ZKResponse response = new ZKResponse();
            response.userinfo = AccessTokenHelper.GetAuthUrl(state,url);
            return response;
        }

        [HttpGet]
        public async Task<ZKResponse> GetUserInfo(string code, string state)
        {
            ZKResponse response = await Task.Factory.StartNew<ZKResponse>(() =>
                {
                    ZKResponse resp = new ZKResponse();
                    AccessToken acs_token = AccessTokenHelper.GetAccessTokenFromWeixinService(code);
                    if (acs_token == null)
                    {
                        resp.isProcessSuccess = false;
                        resp.errMsg = "连接微信服务错误";
                    }
                    else
                    {
                        try
                        {
                            state = state.UrlDecode();
                            string[] STATE = state.Split('_');
                            string wed_identifier = STATE[0].ToString();
                            int layer = STATE[1].toInt32().Value;
                            Wedding wedding = WeddingContainer.sharedInstance.WeddingWithIdentifier(wed_identifier);
                            if (wedding == null)
                            {
                                wedding = Wedding.New(wed_identifier);
                                WeddingContainer.sharedInstance.Add(wedding);
                            }
                            if(!JSSDKAccess.loaded)
                            {
                                JSSDKAccess.Init();
                            }
                            string _ticket = JSSDKAccess.js_ticket;
                            OAuthUserInfo userinfo = OAuthApi.GetUserInfo(acs_token.access_token, acs_token.openid);
                            WeixinUser user = new WeixinUser()
                            {
                                access_token = acs_token,
                                wechat_name = userinfo.nickname,
                                headimgurl = userinfo.headimgurl,
                                redirect_layer = layer,
                                ticket = _ticket,
                                wedding_id = wed_identifier,
                                mylayer = wedding.GetShareLayerFromUserId(acs_token.openid)
                            };
                            if(wedding.AddUser(user))
                            {
                                PushService.PushOnScreenStatToWedding(user.wedding_id,user);
                            }
                            
                            resp.userinfo = user;
                        }
                        catch (Exception e)
                        {
                            resp.isProcessSuccess = false;
                            resp.errMsg = e.Message;
                        }
                    }
                    return resp;
                });
            return response;
        }
    }
}
